package com.atguigu.flink.chapter06.state.operator;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/*
算子状态：
        联合列表状态（UnionListState）
 */
public class OperatorUnionListStateDemo {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);


        env.enableCheckpointing(3000);
        env.socketTextStream("hadoop102",8888)
                .map(new MyMapFunction())
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static class MyMapFunction implements MapFunction<String,String>, CheckpointedFunction {

        List<String> list = new ArrayList<>();
        private ListState<String> state;

        @Override
        public String map(String value) throws Exception {
            if (value.contains("x")){
                System.out.println("程序异常.....");
            }
            String[] words = value.split(" ");
            Collections.addAll(list,words);
            return list.toString();
        }

        //把状态中的值持久化保存
        //周期性的执行：每个并行度执行一次
        @Override
        public void snapshotState(FunctionSnapshotContext ctx) throws Exception {
            state.update(list);
        }

        //初始化状态：从状态中取出数据，存入到你自己需要的数据结构中
        //程序启动的时候执行一次
        @Override
        public void initializeState(FunctionInitializationContext ctx) throws Exception {
            System.out.println("MyMapFunction.initializeState");
            //获取算子状态中的列表状态
            state = ctx.getOperatorStateStore().getUnionListState(new ListStateDescriptor<String>("word", String.class));
            Iterable<String> it = state.get();
            for (String word : it) {
                System.out.println("恢复....." + word);
                list.add(word);
            }
        }
    }
}
